import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/dialog/filter_dialog/custom_filter_right_sheet.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/filter/filter_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/filter/filter_entities_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/ticket_plan_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class SpecialListController extends GetxController {
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  ///外部列表controller
  SpecialPageController? specialPageController;

  // 筛选列表
  List<FilterBean> filterList = [];

  // 选中的作业类型
  List<FilterEntitiesBean> selectType = [];

  // 选中的作业状态
  List<FilterEntitiesBean> selectStateType = [];

  //请求参数
  Map<String, dynamic> queryParameters = {};

  // 搜索字符串
  String? search;

  @override
  void onInit() {
    super.onInit();
    initFilter();
  }

  // 筛选值
  initFilter() async {
    await Future.delayed(const Duration(milliseconds: 500));
    specialPageController = Get.find<SpecialPageController>();
    //添加作业类型筛选
    final List<FilterEntitiesBean> filterWorkType = [];
    for (var value1 in DictDataInfo.specialJobType) {
      filterWorkType.add(FilterEntitiesBean(
        name: value1.dictionaryLabel.toString(),
        value: value1.id,
      ));
    }
    final FilterBean workTypeFilterBean = FilterBean(title: '作业类型', filterList: filterWorkType);
    filterList.add(workTypeFilterBean);

    //添加作业状态
    final List<FilterEntitiesBean> filterStateType = [
      FilterEntitiesBean(
        name: '待开票',
        value: 0,
      ),
      FilterEntitiesBean(
        name: '开票中',
        value: 1,
      ),
      FilterEntitiesBean(
        name: '进行中',
        value: 2,
      ),
      FilterEntitiesBean(
        name: '中断',
        value: 3,
      ),
      FilterEntitiesBean(
        name: '已验收',
        value: 4,
      ),
    ];
    final FilterBean stateTypeFilterBean = FilterBean(title: '作业状态', filterList: filterStateType);
    filterList.add(stateTypeFilterBean);
    update();
  }

  // 获取特殊作业列表数据
  Future<List<TicketPlanEntity>> getPackageDutyData(
    int pageNum,
    int pageSize,
  ) async {
    queryParameters['pageNum'] = pageNum;
    queryParameters['pageSize'] = pageSize;
    queryParameters['keywords'] = search;
    // 作业类型选择数据
    final List<String> index1 = [];
    for (var i in selectType) {
      index1.add(i.value.toString());
    }
    queryParameters['ticketBigTypeIds'] = index1.join(',');

    //作业状态选择数据
    final List<String> index2 = [];
    for (var i in selectStateType) {
      index2.add(i.value.toString());
    }
    queryParameters['type'] = index2.join(',');
    // 获取作业列表接口
    final res = await HttpUtil().generateGetRequest<List<TicketPlanEntity>>(Interface.getTicketPlan, queryParameters: queryParameters).execute();
    List<TicketPlanEntity>? data;
    res.onSuccess((result) {
      data = result.data;
    });
    return data ?? [];
  }

  // 作业计划申请
  void addJobPlanRequest() {
    Get.toNamed(AppRoutes.jobPlanRequest);
  }

  // 进入作业票页面
  // [type] 作业状态 0：待开票 1：开票中 2：进行中 3：中断 4：已验收
  // [ticketBigTypeName] 	作业大类字典名称
  Future<void> toJobTicket(TicketPlanReceiptLists bean) async {
    final int type = bean.type!;
    if (type == 0) {
      //进入作业票流程选择页面
      Get.toNamed(AppRoutes.personnelAllocation, arguments: bean);
    } else {
      //根据流程唯一编码查询流程详情
      final res = await HttpUtil().generateGetRequest<ProcessListEntity>(Interface.getProcessRecordByProcessEncoding,
          queryParameters: {'processEncoding': bean.processEncoding}).execute();

      res.onSuccess((result) {
        final ProcessListEntity entity = result.data!;
        // toPageByType(entity.businessType!, bean);
        toWorkAllPage(entity.businessType!, bean);
      });
    }
  }

  //进入作业总页面
  void toWorkAllPage(String businessType, TicketPlanReceiptLists bean) {
    //跳转到作业总页面
    Get.toNamed(AppRoutes.workAll, arguments: {
      'ticketBean': bean,
      'businessType': businessType,
    });
  }

  // 进入管理作业或继续作业 2:管理作业 3:继续作业
  void toManagementOperation(TicketPlanReceiptLists bean) {
    if (bean.type != 3) {
      Get.toNamed(AppRoutes.manageJobs, arguments: bean);
    } else {
      _jobIngList(bean);
    }
  }

  //进入作业计划详情
  void toJobDetails(String? id, String? identityUserId) {
    Get.toNamed(AppRoutes.jobPlanRequest, arguments: id);
  }

  // 筛选
  void screen() {
    specialPageController!.filterWidget = CustomFilterRightSheet(
      dataList: filterList,
      onConfirm: (List<FilterBean> value) {
        filterList = value;
        for (var i in value) {
          if (i.title == '作业类型') {
            selectType = i.chosenValue;
          }
          if (i.title == '作业状态') {
            selectStateType = i.chosenValue;
          }
        }
        specialPageController!.update();
        refreshPage();
      },
    );
    specialPageController!.update();
    specialPageController!.popRightScaffoldKey.currentState?.openEndDrawer();

    // CustomFilterBottomSheet(
    //   dataList: filterList,
    //   onConfirm: (List<FilterBean> value) {
    //     filterList = value;
    //     for (var i in value) {
    //       if (i.title == '作业类型') {
    //         selectType = i.chosenValue;
    //       }
    //       if (i.title == '作业状态') {
    //         selectStateType = i.chosenValue;
    //       }
    //     }
    //     refreshPage();
    //   },
    // ).showBottomSheetDialog();
  }

  // 搜索
  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  // 继续作业
  void _jobIngList(TicketPlanReceiptLists ticketPlanReceiptLists) async {
    final res = await HttpUtil().generatePostRequest(Interface.interruptWork, queryParameters: {
      'ticketReceiptId': ticketPlanReceiptLists.id,
    }).execute();
    res.onSuccess((result) {
      AppToast.showSuccess('已开始继续作业');
      ticketPlanReceiptLists.type = 2;
      update();
    });
  }
}
